var fcshCacheKey = 'FCSH';
var initHostsConfig = {
    'index': 1,
    0: {check: true, name: 'all hosts', uid: 0, content: {0: '127.0.0.1 localhost'}}
}

function initCahce() {
    if (!localStorage.getItem(fcshCacheKey)) {
        localStorage.setItem(fcshCacheKey, JSON.stringify(initHostsConfig))
    }
}

/**
 * 更新 root hosts content
 * @param uid
 * @param add
 */
function updateRootContent(uid, add) {
    var root = getCache(0)
    if(uid !== 0){
        var rootContent = root.content;
        if (add) {
            rootContent[uid] = getCache(uid).content
        } else {
            delete rootContent[uid]
        }
        root.content = rootContent
    }
    updateCache(0, root)
    if (root.check) {
        rootContentTOProxy()
    } else {
        clearProxy()
    }
}

function rootContentTOProxy() {
    var root = getCache(0)
    var vs = [];
    $.each(root.content, function (k, v) {
        vs.push(v)
    })
    setProxy(vs.join("\n"));
}

/**
 * 设置缓存
 * @param key
 * @param value
 */
function setCache(key, value) {
    var cache = getAllCache()
    cache[key] = value;
    localStorage.setItem(fcshCacheKey, JSON.stringify(cache))
}

/**
 * 获取缓存
 * @param key
 * @returns {*}
 */
function getCache(key) {
    var cache = getAllCache()
    if (cache.hasOwnProperty(key)) {
        return cache[key];
    }
}

/**
 * 删除缓存
 * @param key
 */
function delCache(key) {
    var cache = getAllCache();
    delete cache[key]
    localStorage.setItem(fcshCacheKey, JSON.stringify(cache))
}

/**
 * 获取全部缓存
 * @returns {any}
 */
function getAllCache() {
    return JSON.parse(localStorage.getItem(fcshCacheKey))
}

/**
 * 更新缓存
 * @param key
 * @param value
 */
function updateCache(key, value) {
    var cache = getAllCache()
    if (cache.hasOwnProperty(key)) {
        cache[key] = value;
        localStorage.setItem(fcshCacheKey, JSON.stringify(cache))
    }
}